<template>
  <el-dialog :title="form.infoId ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef"
             :model="form"
             :rules="dataRules"
             label-width="100px"
             v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="选择车系" prop="series">
            <el-select v-model="form.series" placeholder="选择车系" style="width:100%" @change="onSeriesChange">
              <el-option v-for="(item, index) in series"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="选择品牌" prop="brandId">
            <el-select v-model="form.brandId" placeholder="选择品牌" style="width:100%" @change="onBrandChange"
                       :disabled="!form.series">
              <el-option v-for="(item, index) in brandList"
                         :key="index"
                         :value="item.brandId"
                         :label="item.brandName"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="选择型号" prop="modelId">
            <el-select v-model="form.modelId" placeholder="选择型号" style="width:100%" @change="onModelChange"
                       :disabled="!form.brandId">
              <el-option v-for="(item, index) in modelList"
                         :key="index"
                         :value="item.modelId"
                         :label="item.modelName"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="选择款式" prop="styleId">
            <el-select v-model="form.styleId" placeholder="选择款式" style="width:100%"
                       :disabled="!form.modelId">
              <el-option v-for="(item, index) in styleList"
                         :key="index"
                         :value="item.styleId"
                         :label="item.styleName"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="驱动类型" prop="carDrive">
            <el-select v-model="form.carDrive" placeholder="选择驱动类型" style="width:100%">
              <el-option v-for="(item, index) in car_drive"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="排放标准" prop="emissionStandards">
            <el-select v-model="form.emissionStandards" placeholder="选择排放标准" style="width:100%">
              <el-option v-for="(item, index) in emission_standards"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="选择颜色" prop="carColer">
            <el-select v-model="form.carColer" placeholder="选择颜色" style="width:100%">
              <el-option v-for="(item, index) in car_coler"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="变速箱" prop="cearbox">
            <el-select v-model="form.cearbox" placeholder="选择变数箱" style="width:100%">
              <el-option v-for="(item, index) in cearbox"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="座位数" prop="seatsNums">
            <el-select v-model="form.seatsNums" placeholder="选择座位数" style="width:100%">
              <el-option v-for="(item, index) in seats_nums"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="燃料类型" prop="fuelType">
            <el-select v-model="form.fuelType" placeholder="选择燃料类型" style="width:100%">
              <el-option v-for="(item, index) in fuel_type"
                         :key="index"
                         :value="item.value"
                         :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="收车成本" prop="costOfCollection">
            <el-input v-model="form.costOfCollection"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="售价" prop="sellingPrice">
            <el-input v-model="form.sellingPrice"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20" >
          <el-form-item label="上下架状态" prop="status">
            <el-radio v-model="form.status"
                      :label="item.value"
                      border
                      v-for="(item, index) in status"
                      :key="index">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="出厂时间" prop="factoryTime">
            <el-date-picker
                v-model="form.factoryTime"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <!-- 修改标签选择部分 -->
        <el-col :span="24" class="mb20">
          <el-form-item label="选择标签" prop="lableId">
            <el-row>
              <el-space wrap :size="8">
                <button
                    v-for="(item, index) in labelList"
                    :key="index"
                    class="label-item"
                    :style="{backgroundColor: item.color, color: '#000000'}"
                    :class="{active: form.lableId === item.labelId}"
                    @click="selectLabel(item.labelId)"
                    type="button"
                >
                  {{ item.labelName }}
                </button>
              </el-space>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item prop="pictures">
            <ImageUpload
                v-model:imageUrl="form.pictures"
                :file-url="true"
                :action="uploadAction"
                :headers="uploadHeaders"
            >
              <template #empty>
                <el-icon><Promotion /></el-icon>
                <span>请上传图片</span>
              </template>
            </ImageUpload>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark"
                      type="textarea"
                      placeholder="请输入备注"
                      :rows="4"
                      class="input-width"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="CarInfoDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj, getBrands, getModels, getStyles } from '/@/api/yu/carInfo';
import { getAllLabel } from "/@/api/yu/carInfo";

const emit = defineEmits(['refresh']);
const ImageUpload = defineAsyncComponent(() => import('/@/components/Upload/Image.vue'));
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 级联数据
const seriesList = ref<any[]>([])
const brandList = ref<any[]>([])
const modelList = ref<any[]>([])
const styleList = ref<any[]>([])
const labelList = ref<any[]>([]) // 标签列表
// 上传配置
const uploadAction = import.meta.env.VITE_ADMIN_PROXY_PATH + '/file/upload';
const uploadHeaders = {
  'Authorization': 'Bearer ' + localStorage.getItem('token') // 根据实际认证方式调整
};
// 定义字典
const { car_coler,seats_nums,emission_standards,cearbox,fuel_type,car_drive,series,status } =
    useDict('car_coler','seats_nums','emission_standards','cearbox','fuel_type','car_drive','series','status')
// 提交表单数据
const form = reactive({
  infoId: '',
  carCode: '',
  styleId: '',
  carDrive: '',
  emissionStandards: '',
  carColer: '',
  cearbox: '',
  seatsNums: '',
  fuelType: '',
  costOfCollection: '',
  sellingPrice: '',
  status: '',
  factoryTime: '',
  lableId: '',
  isSelling: '',
  pictures: '',
  remark: '',
  series: '',
  brandId: '',
  modelId: '',
});
// 定义校验规则
const dataRules = ref({
  series: [{ required: true, message: '车系不能为空', trigger: 'blur' }],
  brandId: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  modelId: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
  styleId: [{ required: true, message: '款式不能为空', trigger: 'blur' }],
  carDrive: [{ required: true, message: '汽车驱动不能为空', trigger: 'blur' }],
  emissionStandards: [{ required: true, message: '排放标准不能为空', trigger: 'blur' }],
  carColer: [{ required: true, message: '颜色不能为空', trigger: 'blur' }],
  cearbox: [{ required: true, message: '变数箱不能为空', trigger: 'blur' }],
  seatsNums: [{ required: true, message: '座位数不能为空', trigger: 'blur' }],
  fuelType: [{ required: true, message: '燃料类型不能为空', trigger: 'blur' }],
  sellingPrice: [{ required: true, message: '售价不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  factoryTime: [{ required: true, message: '出厂时间不能为空', trigger: 'blur' }],
  pictures: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
  costOfCollection: [{ required: true, message: '成本价不能为空', trigger: 'blur' }]
});
// 车系变更事件
const onSeriesChange = async (series: string) => {
  // 清空下级数据
  form.brandId = '';
  form.modelId = '';
  form.styleId = '';
  brandList.value = [];
  modelList.value = [];
  styleList.value = [];
  if (!series) return;
  try {
    const res = await getBrands(series);
    brandList.value = res.data || [];
  } catch (error) {
    console.error('获取品牌列表失败', error);
    useMessage().error('获取品牌列表失败');
  }
};
// 品牌变更事件
const onBrandChange = async (brandId: number) => {
  // 清空下级数据
  form.modelId = '';
  form.styleId = '';
  modelList.value = [];
  styleList.value = [];
  if (!brandId) return;
  try {
    const res = await getModels(brandId);
    modelList.value = res.data || [];
  } catch (error) {
    console.error('获取型号列表失败', error);
    useMessage().error('获取型号列表失败');
  }
};
// 型号变更事件
const onModelChange = async (modelId: number) => {
  // 清空下级数据
  form.styleId = '';
  styleList.value = [];
  if (!modelId) return;
  try {
    const res = await getStyles(modelId);
    styleList.value = res.data || [];
  } catch (error) {
    console.error('获取款式列表失败', error);
    useMessage().error('获取款式列表失败');
  }
};
// 标签选择
const selectLabel = (labelId: number) => {
  form.lableId = form.lableId === labelId ? '' : labelId;
};
// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.infoId = ''
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
    // 清空级联数据
    form.series = '';
    form.brandId = '';
    form.modelId = '';
    form.styleId = '';
    brandList.value = [];
    modelList.value = [];
    styleList.value = [];
  });
  // 获取carInfo信息
  if (id) {
    form.infoId = id
    getcarInfoData(id)
  }
};
// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;
  try {
    loading.value = true;
    form.infoId ? await putObj(form) : await addObj(form);
    useMessage().success(form.infoId ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};
// 获取所有标签列表
const fetchAllLabels = async () => {
  try {
    const res = await getAllLabel();
    labelList.value = res.data || [];
  } catch (error) {
    console.error('获取标签列表失败:', error);
    useMessage().error('获取标签列表失败');
  }
};
// 初始化表单数据
const getcarInfoData = async (id: string) => {
  loading.value = true;
  try {
    const res = await getObj(id);
    const data = res.data;
    // 1. 先根据 series 加载品牌
    if (data.series) {
      await onSeriesChange(data.series);
    }
    // 2. 再根据 brandId 加载型号
    if (data.brandId) {
      await onBrandChange(data.brandId);
    }
    // 3. 再根据 modelId 加载款式
    if (data.modelId) {
      await onModelChange(data.modelId);
    }
    // 4. 所有列表就绪后，一次性回填表单
    Object.assign(form, data);
  } finally {
    loading.value = false;
  }
};
// 初始化加载
onMounted(() => {
  fetchAllLabels();
});
// 暴露变量
defineExpose({
  openDialog
});
</script>
<style scoped>
/* 标签样式 */
.label-item {
  width: 75px;
  font-size: 13px;
  font-weight: 500;
  height: 30px;
  padding: 4px 10px;
  border-radius: 4px;
  min-width: 50px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.label-item.active {
  border: 2px solid #000000;
  box-sizing: border-box;
}

/* 图片占位符样式 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.image-slot .el-icon {
  font-size: 20px;
}
</style>
